<template>
  <div class="video-preview" :style="`width:${realWidth};height:${realHeight};`">
    <!-- 视频预览封面 -->
    <div class="video-container">
      <video
          ref="previewRef"
          :src="`${realSrc}`"
          :style="`width:100%;height:100%;`"
          @loadedmetadata="handleLoaded"
      >
        您的浏览器不支持 video 标签。
      </video>
      <div class="play-button" @click="play">
        <icon icon="ep:video-play" size="40"/>
      </div>
    </div>
  </div>
  <a-modal v-model:visible="visible" width="740px" title="视频预览" render-to-body :before-close="handleDialogClose" :footer="false">
    <div class="aspect-video overflow-hidden" style="height: 580px">
      <video ref="videoRef" class="video-fit" controls>
        <source :src="realSrc" type="video/mp4"/>
      </video>
    </div>
  </a-modal>
</template>

<script setup>
import {computed, ref, onMounted} from "vue";
import {isExternal} from "@/utils/utils";

const props = defineProps({
  src: {
    type: String,
    default: ""
  },
  width: {
    type: [Number, String],
    default: ""
  },
  height: {
    type: [Number, String],
    default: ""
  }
});

const previewRef = ref();
const videoRef = ref();
const visible = ref(false);
const loaded = ref(false);

const realSrc = computed(() => {
  if (!props.src) {
    return;
  }
  let real_src = props.src.split(",")[0];
  if (isExternal(real_src)) {
    return real_src;
  }
  return import.meta.env.VITE_IMG_URL + real_src;
});

const realWidth = computed(() =>
    typeof props.width === "string" ? props.width : `${props.width}px`
);

const realHeight = computed(() =>
    typeof props.height === "string" ? props.height : `${props.height}px`
);

const handleLoaded = () => {
  loaded.value = true;
  // 加载后暂停预览视频，只显示第一帧
  if (previewRef.value) {
    previewRef.value.currentTime = 0;
    previewRef.value.pause();
  }
};

const handleDialogClose = () => {
  if (videoRef.value) {
    videoRef.value.pause();
  }
  visible.value = false;
};

// 点击播放按钮时打开弹窗
const play = () => {
  visible.value = true
};

onMounted(() => {
  // 确保预览视频静音
  if (previewRef.value) {
    previewRef.value.muted = true;
  }
});
</script>

<style scoped lang="scss">
.video-container {
  position: relative;
  width: 100%;
  height: 100%;

  &:hover {
    .play-button {
      opacity: 1;
    }
  }
}

.play-button {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.3s ease;
  color: white;

  &:hover {
    background-color: rgba(0, 0, 0, 0.7);
  }
}

:deep(.video-dialog) {
  z-index: 2000;
}

.video-fit {
  width: 100%;
  height: 100%;
  object-fit: contain;
}
</style>
